package com.limh.readers.activity

import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.content.Intent
import android.content.SharedPreferences
import android.os.Handler
import android.os.Message
import android.view.inputmethod.InputMethodManager
import android.widget.Toast
import butterknife.ButterKnife
import butterknife.Unbinder
import com.limh.readers.comm.AppConfig


abstract class BaseActivity : AppCompatActivity() {
    private var appConfig: AppConfig? = null
    lateinit var mUnbinder: Unbinder
    lateinit var userPreference: SharedPreferences
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        findView()
        mUnbinder = ButterKnife.bind(this)
        appConfig = AppConfig.getInstance()
        userPreference = getSharedPreferences("USER", Context.MODE_PRIVATE)
        initViews()
        initDatas()
    }

    abstract fun findView()
    abstract fun initViews()
    abstract fun initDatas()

    /**
     * 启动一个Activity
     */
    fun openActivity(tagClass: Class<*>) {
        val intent = Intent()
        intent.setClass(this, tagClass)
        startActivity(intent)
    }

    /**
     * 启动Service
     */
    fun openService(tagClass: Class<*>) {
        val intent = Intent()
        intent.setClass(this, tagClass)
        startService(intent)
    }
    /**
     * 稍长时间展示toast
     */
    fun showToastLong(msg: String) {
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show()
    }

    /**
     * 短时间展示toast
     */
    fun showToastShort(msg: String) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
    }

    /**
     * 发送消息
     * 需要在继承的activity中定义一个handler
     * 例如：
     * private val handler = Handler(Handler.Callback { msg ->
     *
     *   false
     * })
     */
    fun sendMsg(msg: String, what: Int, handler: Handler) {
        val bundle = Bundle()
        bundle.putString("msg", msg)
        val message = Message()
        message.what = what
        message.data = bundle
        handler.sendMessage(message)
    }

    /**
     * 隐藏软件盘
     */
    fun Activity.hideKeyboard(): Boolean {
        val view = currentFocus
        view?.let {
            val inputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE)
                    as InputMethodManager
            return inputMethodManager.hideSoftInputFromWindow(view.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
        }
        return false
    }

    override fun onDestroy() {
        super.onDestroy()
        mUnbinder.unbind()
    }
}
